#!/bin/sh -e

# Make patroni process real-time if we have enough permissions
CHRT="chrt -Rr 99"
if ! $CHRT true 2> /dev/null; then
    CHRT=""
fi

CHPST="chpst -u postgres"
if ! $CHPST true 2> /dev/null; then
    CHPST=""
fi

# Exclude shared memory from coredump
if ! echo 0x31 > /proc/self/coredump_filter
then
    echo "Failed to enable coredump shared memory filter"
fi

# Enable core dumps
if ! ulimit -c unlimited
then
   echo "Failed to set unlimited size for coredump"
fi

# Only small subset of environment variables is allowed. We don't want accidentally disclose sensitive information
for E in $(printenv -0 | tr '\n' ' ' | sed 's/\x00/\n/g' | grep -vE '^(KUBERNETES_(SERVICE|PORT|ROLE)[_=]|((POD_(IP|NAMESPACE))|HOSTNAME|PATH|PGHOME|LC_ALL|ENABLE_PG_MON)=)' | sed 's/=.*//g'); do
    unset $E
done

exec 2>&1
exec $CHRT $CHPST env HOME=/home/postgres patroni /home/postgres/postgres.yml
